package com.gjxx.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 通道初始化
 *
 * @author lics
 * @version 1.0.0
 * @date 2023/6/1 13:12
 */
public class MyNettyChannelInitializer extends ChannelInitializer<Channel> {

    @Override
    protected void initChannel(Channel channel) {
        /**
         * 处理TCP请求
         * readerIdleTimeSeconds	读超时。即当在指定的时间间隔内没有从Channel读取到数据时，会触发一个READER_IDLE的IdleStateEvent事件
         * writerIdleTimeSeconds	写超时。即当在指定的时间间隔内没有数据写入到Channel时，会触发一个WRITER_IDLE的IdleStateEvent事件
         * allIdleTimeSeconds	读/写超时。即当在指定的时间间隔内没有读或写操作时，会触发一个ALL_IDLE的IdleStateEvent事件
         */
        channel.pipeline().addLast(new IdleStateHandler(2 * 60, 0, 2 * 60));
        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.wrappedBuffer(new byte[]{0x7e}), Unpooled.wrappedBuffer(new byte[]{0x7e, 0x7e})));
        // ChannelOutboundHandler，依照逆序执行
//        channel.pipeline().addLast("encoder", new MyEncoder());
        // 属于ChannelInboundHandler，依照顺序执行
        channel.pipeline().addLast("decoder", new MyDecoder());
        // 自定义TCP请求的处理器
        channel.pipeline().addLast(new TcpRequestHandler());
    }

}
